package com.hys.resourceserver;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class ResourceConfig {

    @Bean
    public SecurityFilterChain resourceServerSecurityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http.csrf(AbstractHttpConfigurer::disable);
        http.cors(AbstractHttpConfigurer::disable);
        //最好关闭,但不是必须的,使用jwt 不在使用session作为会话
        http.sessionManagement(AbstractHttpConfigurer::disable);
        //必须设置,否则会跳转自己的登录
        http.oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()));
        http.authorizeHttpRequests(authorize -> {
                    authorize.requestMatchers( "/assets/**", "/webjars/**").permitAll();
                    authorize.requestMatchers(HttpMethod.OPTIONS).permitAll();
                    authorize.requestMatchers("/error/**").permitAll();
                    //不需要自己的登录了,使用授权服务器的
                    //authorize.requestMatchers("/login/**").permitAll();
                    //权限服务器登录后跳转的路径,必须是公开的
                    //和授权服务器配置一致,跳转的url
                    authorize.requestMatchers("/actuator/**").permitAll();
                    authorize.anyRequest().authenticated();
                });
        http.formLogin(Customizer.withDefaults());
        // @formatter:on
        return http.build();
    }
}
